package com.lezhi.socialgram.service.sys.impl;

import com.lezhi.socialgram.enums.ResultEnum;
import com.lezhi.socialgram.exception.SocialGramException;
import com.lezhi.socialgram.mapper.sys.TelNumSignInMapper;
import com.lezhi.socialgram.model.lbs.FootPrint;
import com.lezhi.socialgram.model.sys.TelNumSignInUser;
import com.lezhi.socialgram.service.im.IMService;
import com.lezhi.socialgram.service.lbs.LbsService;
import com.lezhi.socialgram.service.sys.SignInService;
import com.lezhi.socialgram.util.*;
import com.lezhi.socialgram.dto.SignInData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by daizhen on 2017/3/29.
 */
@Service
public class SignInServiceImpl implements SignInService {

    private static final Logger logger = LoggerFactory.getLogger(SignInServiceImpl.class);

    @Autowired
    TelNumSignInMapper telNumSignInMapper;

    @Autowired
    LbsService lbsService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    IMService imService;

    @Override
    public Result signInWithTelNumAndPassword(TelNumSignInUser telNumSignInUser) {
        try {
            //判断用户存不存在
            String indexByTel = XUtil.getTableNameIndexByTel(telNumSignInUser.getTelNum());
            String table = Param.T_USER_TEL_NUM_INDEX_TABLE_PREFIX + indexByTel;
            telNumSignInUser.setTable(table);
            TelNumSignInUser userIndex = telNumSignInMapper.getUserId(telNumSignInUser);
            if (userIndex == null)
                return ResultUtils.error(ResultEnum.AUTH_FAILED);
            telNumSignInUser.setTable(TableUtils.getTableNameWithId(TelNumSignInUser.class, userIndex.getUserId(), 10));
            telNumSignInUser.setUserId(userIndex.getUserId());
            //判断账号的状态
            int accountStatus = telNumSignInMapper.queryAccountStatus(telNumSignInUser);
            if (accountStatus == 1)
                return ResultUtils.error(ResultEnum.ACCOUNT_LOCKED);
            //认证
            String md5DigestAsHex = DigestUtils.md5DigestAsHex(telNumSignInUser.getPassword().getBytes());
            String ms5Password = DigestUtils.md5DigestAsHex((userIndex.getUserId() + md5DigestAsHex).getBytes());
            telNumSignInUser.setPassword(ms5Password);
            TelNumSignInUser signInUser = telNumSignInMapper.auth(telNumSignInUser);
            if (signInUser == null)
                return ResultUtils.error(ResultEnum.AUTH_FAILED);
            //更新用户信息
            //更新足迹
            telNumSignInUser.setRemoteIP(XUtil.getRemoteAddr(request));
            String footPrintJson = signInUser.getFootPrints();
            if (footPrintJson != null) {
                List<FootPrint> footPrints = JsonUtils.jsonToList(footPrintJson, FootPrint.class);
                footPrints.add(new FootPrint(telNumSignInUser.getCountry(), telNumSignInUser.getRegion(),
                        telNumSignInUser.getCity(), telNumSignInUser.getCounty()));
                telNumSignInUser.setFootPrints(JsonUtils.objectToJson(footPrints));
            }
            telNumSignInMapper.signInWithTelNum(telNumSignInUser);
            new Thread(() -> {
                //更新位置
                try {
                    lbsService.indexUser(telNumSignInUser);
                    imService.connect(telNumSignInUser.getUserId());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            }).start();
            return ResultUtils.success(new SignInData(telNumSignInUser.getUserId(), false));
        } catch (Exception e) {
            e.printStackTrace();
            throw new SocialGramException(ResultEnum.INTERNAL_ERROR);
        }
    }
}
